package xt3FuturesUser

import (
	"crypto/hmac"
	"crypto/sha256"
	"encoding/hex"
	"encoding/json"
	"fmt"

	"time"

	"github.com/astaxie/beego/logs"

	r "github.com/solos/requests"
)

const (
	Path          = "/future/user/v1/user/listen-key"
	XTContractAPI = "http://fapi.xt-qa.com" + Path
)

type XTContractListkey struct {
}

type Response struct {
	ReturnCode interface{} `json:"returnCode"`
	MsgInfo    interface{} `json:"msgInfo"`
	Error      interface{} `json:"error"`
	Result     string      `json:"result"`
}

func (xt *XTContractListkey) Request(accesskey, secretkey string) (data string) {

	kwargs := r.M{}
	kwargs["timeout"] = 10
	utc := time.Now().UnixNano() / 1e6

	signkey := fmt.Sprintf("xt-validate-appkey=%s&xt-validate-timestamp=%d#%s", accesskey, utc, Path)
	h := hmac.New(sha256.New, []byte(secretkey))
	h.Write([]byte(signkey))
	// 设定请求头
	// fmt.Println("[UTC] ", utc)
	headers := map[string]string{
		"xt-validate-appkey":     accesskey,
		"xt-validate-timestamp":  fmt.Sprintf("%d", utc),
		"xt-validate-signature":  hex.EncodeToString(h.Sum(nil)),
		"xt-validate-algorithms": "HmacSHA256",
		"content-Type":           "application/x-www-form-urlencoded",
	}

	// 实例化一个请求对象
	req := &r.Request{Args: kwargs}
	resp, err := req.MakeRequest("GET", XTContractAPI, r.Headers(headers))
	if err != nil {
		logs.Debug("[xt-contract-user-api] 获取Token失败...", err)
		return
	}

	dataBytes := []byte(resp.Content)
	// 反序列化成map
	res := new(Response)
	err = json.Unmarshal(dataBytes, &res)
	if err != nil {
		logs.Debug("[xt-contract-user-api] 反序列化成map失败...", err, string(dataBytes))

	}
	data = res.Result
	return
}
